Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [#521] User can custom recover when a request panic #103

Merged
merged 87 commits into from
Dec 27, 2024

Conversation

KlassnayaAfrodita
Copy link
Contributor

@KlassnayaAfrodita KlassnayaAfrodita commented Nov 15, 2024

πŸ“‘ Description

Closes goravel/goravel#521

@coderabbitai summary

βœ… Checks

  • Added test cases for my code

@KlassnayaAfrodita KlassnayaAfrodita requested a review from a team as a code owner November 15, 2024 20:06
Copy link

coderabbitai bot commented Nov 15, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

🏷️ Labels to auto review (1)
  • πŸš€ Review Ready

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov-commenter
Copy link

codecov-commenter commented Nov 15, 2024

Codecov Report

Attention: Patch coverage is 82.60870% with 4 lines in your changes missing coverage. Please review.

Project coverage is 78.15%. Comparing base (5a68f28) to head (cdf7d2f).
Report is 53 commits behind head on master.

Files with missing lines Patch % Lines
route.go 78.57% 2 Missing and 1 partial ⚠️
facades/gin.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #103      +/-   ##
==========================================
- Coverage   79.29%   78.15%   -1.14%     
==========================================
  Files          12       16       +4     
  Lines         874     1158     +284     
==========================================
+ Hits          693      905     +212     
- Misses        151      211      +60     
- Partials       30       42      +12     

β˜” View full report in Codecov by Sentry.
πŸ“’ Have feedback on the report? Share it here.

context_request.go Outdated Show resolved Hide resolved
context_request.go Outdated Show resolved Hide resolved
context_request_test.go Outdated Show resolved Hide resolved
facades/gin.go Outdated Show resolved Hide resolved
middleware_timeout.go Outdated Show resolved Hide resolved
route.go Outdated Show resolved Hide resolved
route.go Outdated
}
middlewares = append(defaultMiddlewares, middlewares...)
r.setMiddlewares(middlewares)
}

func (r *Route) Recover(recoverFunc func(ctx *gin.Context, err interface{})) {
r.instance.Use(func(ctx *gin.Context) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a CustomRecovery method in Gin, we can use it directly.

image

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will we end up using gin.CustomRecovery?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it can be used directly, yes, we can.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is CustomRecovery suitable, please?

@@ -35,13 +36,18 @@ func (receiver *ServiceProvider) Boot(app foundation.Application) {

if ConfigFacade = app.MakeConfig(); ConfigFacade == nil {
color.Errorln(errors.ConfigFacadeNotSet.SetModule(module))
shutdownOnCriticalError("ConfigFacade is not set")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's unnecessary for now, we want to print a warning instead of interrupting.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to remove the function totally.

view.go Outdated Show resolved Hide resolved
view.go Outdated Show resolved Hide resolved
@KlassnayaAfrodita
Copy link
Contributor Author

can you give me a direction to solve the error?

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty good now, could you add some test cases for the new logic?

@@ -44,11 +44,12 @@ func NewContextRequest(ctx *Context, log log.Log, validation contractsvalidate.V
request := contextRequestPool.Get().(*ContextRequest)
httpBody, err := getHttpBody(ctx)
if err != nil {
log.Error(fmt.Sprintf("%+v", err))
LogFacade.Error(fmt.Sprintf("%+v", errors.Unwrap(err)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't need to modify this, I optimized the code in a previous PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please modify this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do I need to return log?
patch-3 of my fork currently uses LogFacade

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

log is fine, please update your branch.

facades/gin.go Show resolved Hide resolved
route.go Outdated Show resolved Hide resolved
service_provider.go Outdated Show resolved Hide resolved
view.go Outdated Show resolved Hide resolved
Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, please add some test cases for the new logic, then we can merge this.

@@ -44,11 +44,12 @@ func NewContextRequest(ctx *Context, log log.Log, validation contractsvalidate.V
request := contextRequestPool.Get().(*ContextRequest)
httpBody, err := getHttpBody(ctx)
if err != nil {
log.Error(fmt.Sprintf("%+v", err))
LogFacade.Error(fmt.Sprintf("%+v", errors.Unwrap(err)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please modify this

@KlassnayaAfrodita
Copy link
Contributor Author

Great, please add some test cases for the new logic, then we can merge this.

I wrote two tests for a custom function and a default one. I need to create a new test file or add to an existing one (for example route_test.go). for the default case you need to use route.Recover(nil)
I want to do route.Recover()
for this I want to add

func (r *Route) SetRecover(callback func(ctx context.Context, err any)){
    globalRecoverCallback = callback
}

@hwbrzzl
Copy link
Contributor

hwbrzzl commented Dec 24, 2024

You don't need to call route.Recover() when testing the default action.

@KlassnayaAfrodita
Copy link
Contributor Author

#103 (comment)
do I need to return log?
patch-3 of my fork currently uses LogFacade

route_test.go Outdated
"github.com/gin-gonic/gin/render"
contractshttp "github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/validation"
configmocks "github.com/goravel/framework/mocks/config"
"github.com/stretchr/testify/assert"
)

func TestRecoverWithCustomCallback(t *testing.T) {
mockConfig := &configmocks.Config{}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
mockConfig := &configmocks.Config{}
mockConfig := configmocks.NewConfig(t)

route.go Outdated
}
}

func (r *Route) Recover(callback func(ctx context.Context, err any)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, mistake, should be:

Suggested change
func (r *Route) Recover(callback func(ctx context.Context, err any)) {
func (r *Route) Recover(callback func(ctx httpcontract.Context, err any)) {

Please modify https://github.com/goravel/framework/pull/723/files#diff-37b488415e77368d5640d20902b15e5603864dc8c5c1e715bc36e2a8510b81f8R19 synchronously.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test case to test the custom recover as well.

}()

select {
case <-done:
case <-ctx.Request().Origin().Context().Done():
if errors.Is(ctx.Request().Origin().Context().Err(), context.DeadlineExceeded) {
case <-timeoutCtx.Done():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch

"github.com/gin-gonic/gin/render"
contractshttp "github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/validation"
configmocks "github.com/goravel/framework/mocks/config"
"github.com/stretchr/testify/assert"
)

func TestRecoverWithCustomCallback(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test case to test the default recover as well.

assert.Equal(t, http.StatusInternalServerError, w.Code)

mockConfig.AssertExpectations(t)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test case is pretty good.

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect, please create a fiber like this. πŸ‘

@hwbrzzl
Copy link
Contributor

hwbrzzl commented Dec 26, 2024

And another information, we are going to release v1.15 next week. It would be great if we could complete this issue this week.

@hwbrzzl hwbrzzl merged commit 1cbcae6 into goravel:master Dec 27, 2024
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

✨ [Feature] User can custom recover when a request panic
4 participants